package com.lemon.smartsafety.ui.activity.user;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatRadioButton;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TableRow;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.android.http.AesEncryptor;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.BuildConfig;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.common.AreaVo;
import com.lemon.smartsafety.entity.common.RoleVo;
import com.lemon.smartsafety.entity.event.common.AreaSelectEvent;
import com.lemon.smartsafety.entity.event.common.SelectItemEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.UserServices;
import com.lemon.smartsafety.listener.AreaType;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.ui.activity.common.AreaProvinceActivity;
import com.lemon.smartsafety.ui.activity.common.RoleActivity;
import com.lemon.smartsafety.utils.RulesUtils;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.PinyinUtils;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.KeyBoardUtils;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.utils.common.ValidateUtils;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.greenrobot.eventbus.Subscribe;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Cooliean on 16/4/6.
 */
public class RegisterActivity extends SwipeBackActivity {
    @Bind(R.id.metUserName)
    MaterialEditText     metUserName;
    @Bind(R.id.metLoginName)
    MaterialEditText     metLoginName;
    @Bind(R.id.radioMale)
    AppCompatRadioButton radioMale;
    @Bind(R.id.radioFemale)
    AppCompatRadioButton radioFemale;
    @Bind(R.id.metPassword)
    MaterialEditText     metPassword;
    @Bind(R.id.metConfirmPassword)
    MaterialEditText     metConfirmPassword;
    @Bind(R.id.metMobile)
    MaterialEditText     metMobile;
    @Bind(R.id.metArea)
    MaterialEditText     metArea;
    @Bind(R.id.rowArea)
    TableRow             rowArea;
    @Bind(R.id.metRole)
    MaterialEditText     metRole;
    @Bind(R.id.rowRole)
    TableRow             rowRole;
    @Bind(R.id.metCid)
    MaterialEditText     metCid;
    @Bind(R.id.metPost)
    MaterialEditText     metPost;
    @Bind(R.id.btn_submit)
    Button               btnSubmit;


    private AreaVo areaProvince;
    private AreaVo areaCity;

    private RoleVo roleVo;


    @Override
    protected void initTitle() {
        setBarTitle("注册");
    }


    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(RegisterActivity.this);

    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            callFinish();
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected int getContentViewId() {
        return R.layout.activity_register_prop;
    }


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
    }

    @Override
    protected void initViews() {
        super.initViews();
        initDebugValue();
    }


    private void initDebugValue() {
        if (BuildConfig.DEBUG) {
            metUserName.setText("陈华健");
            metLoginName.setText("cooliean");
            metPassword.setText("111111");
            metConfirmPassword.setText("111111");
            metMobile.setText("13666227528");
        }
    }

    private boolean validateForm() {
        if (TextUtils.isEmpty(metUserName.getText().toString().trim())) {
            metUserName.setError("请填写用户名");
            mHUDUtil.showErrorTip("请填写用户名");
            return false;
        }


        if (TextUtils.isEmpty(metLoginName.getText().toString().trim())) {
            metLoginName.setError("请填写登录名");
            mHUDUtil.showErrorTip("请填写登录名");
            return false;
        }


        String sPassword = metPassword.getText().toString();
        if (TextUtils.isEmpty(sPassword)) {
            metPassword.setError("请填写密码");
            mHUDUtil.showErrorTip("请填写密码");
            return false;
        }

        String sConfirmPassword = metConfirmPassword.getText().toString();
        if (TextUtils.isEmpty(sConfirmPassword)) {
            metConfirmPassword.setError("请填写确认密码");
            mHUDUtil.showErrorTip("请填写确认密码");
            return false;
        }


        if (!sPassword.equals(sConfirmPassword)) {
            mHUDUtil.showErrorTip("两次密码不一致");
            return false;
        }


        if (TextUtils.isEmpty(metMobile.getText().toString())) {
            metMobile.setError("请填写手机号码");
            mHUDUtil.showErrorTip("请填写手机号码");
            return false;
        }


     /*   if (!ValidateUtils.isMobile(metMobile.getText().toString().trim())) {
            mHUDUtil.showErrorTip("手机号码不合法");
            return false;
        }*/

        if (!RulesUtils.isPhoneNumberValid(metMobile.getText().toString().trim())) {
            mHUDUtil.showErrorTip("手机号码不合法");
            metMobile.setError("手机号码不合法");
            return false;
        }


        if (!TextUtils.isEmpty(metCid.getText().toString().trim()) && !ValidateUtils.isCid(metCid.getText().toString().trim())) {
            metCid.setError("身份证号码不合法");
            mHUDUtil.showErrorTip("身份证号码不合法");
            return false;
        }


        if (areaProvince == null || areaCity == null) {
            mHUDUtil.showErrorTip("请选择注册地域（省市）");
            return false;
        }


        if (roleVo == null) {
            mHUDUtil.showErrorTip("请选择注册角色");
            return false;
        }

        return true;
    }

    @OnClick({R.id.btn_submit})
    public void onSubmitClick(View view) {
        if (view.getId() == R.id.btn_submit) {
            if (!validateForm()) {
                return;
            }

            getConfirmDialog("是否提交注册?", new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    if (which == DialogAction.POSITIVE) {
                        doAction();
                    }
                }
            }).show();

        }
    }


    @OnClick({R.id.metArea, R.id.rowArea, R.id.metRole, R.id.rowRole})
    public void onClick(View view) {
        if (view.getId() == R.id.metArea || view.getId() == R.id.rowArea) {//地域选择
            Bundle bundle = new Bundle();
            bundle.putBoolean(BundleKey.IS_FOR_REGISTER, true);
            UIHelper.showActivity(RegisterActivity.this, bundle, AreaProvinceActivity.class);
        } else if (view.getId() == R.id.metRole || view.getId() == R.id.rowRole) {//角色选择
            Bundle bundle = new Bundle();
            if (roleVo != null) {
                bundle.putString(BundleKey.OLD_SELECT_VALUE, StringUtils.nullValue(roleVo.getValue()));
            }
            UIHelper.showActivity(RegisterActivity.this, bundle, RoleActivity.class);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        KeyBoardUtils.closeSoftInput(this);
    }

    @Subscribe
    public void onEventMainThread(AreaSelectEvent event) {
        if (AreaType.PROVINCE == event.getType()) {
            areaProvince = event.getData();
        } else if (AreaType.CITY == event.getType()) {
            areaCity = event.getData();
        }
        setAreaViewValue();
    }

    @Subscribe
    public void onEventMainThread(SelectItemEvent event) {
        if (EventTag.TAG_ROLE.equals(event.getTag())) {
            roleVo = (RoleVo) event.getData();
            metRole.setText(roleVo.getTitle());
        }
    }

    private void setAreaViewValue() {
        if (areaProvince != null && areaCity != null) {
            String formatString = "%s-%s";
            metArea.setText(String.format(formatString, StringUtils.nullValue(areaProvince.getTitle()), StringUtils.nullValue(areaCity.getTitle())));
        } else if (areaProvince != null && areaCity == null) {
            metArea.setText(StringUtils.nullValue(areaProvince.getTitle()));
        }
    }


    private void doAction() {
        String sex = "0";
        if (radioFemale.isChecked()) {
            sex = "1";
        }

        LemonRequestParams params = new LemonRequestParams();
        params.put("registername", metUserName.getText().toString().trim());
        params.put("loginname", metLoginName.getText().toString().trim());
        params.put("pwd", AesEncryptor.encrypt(metPassword.getText().toString().trim()));
        params.put("sex", sex);
        params.put("role", StringUtils.nullValue(roleVo.getValue()));
        params.put("mobile", metMobile.getText().toString().trim());
        params.put("idcard", metCid.getText().toString().trim());
        params.put("city", areaCity.getVoId());
        params.put("post", metPost.getText().toString().trim());
        params.put("namepy", PinyinUtils.getPinyin(metUserName.getText().toString().trim()));


        UserServices.init().doRegister(params);
    }


    @Subscribe
    public void onEventMainThread(final HttpCallbackEvent event) {
        if (EventTag.TAG_REGISTER_ACTION.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showInfoTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            mSharedPreferencesHelper.loginOut();
                            mSharedPreferencesHelper.setLoginName(metLoginName.getText().toString());
                            callFinish();
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }

}
